<?php
Core::getInstance()->sys_load_class('Model',false);
Core::getInstance()->app_load_class('Template',false);
Core::getInstance()->app_load_class('Admin',false);
Core::getInstance()->sys_load_class('Character',false);
class Tpl extends Admin{

	/*Singleton{{{*/
	public static function getInstance(){
		static $instance=null;
		if($instance===null){ 
			$instance = new self();
		}
		return $instance;
	}
	private function __construct(){}
	private function __clone(){
		trigger_error("Clone is not allowed.", E_USER_ERROR);
	}
	/*}}}*/

	public function indexAction(){
	}

	public function addAction(){
		$title= '添加页面';
		if(isset($_GET['id'])){
			$title= '页面参数设定';
			$id = intval($_GET['id']);
			$tpl = new Template();
			$data = $tpl->getOneData($id);
		}
		include $this->display('tpl_add.tpl.php');
	}
	public function addSubmitAction(){
		if(strpos($_SERVER['HTTP_REFERER'],DOMAIN)===false){ // 外部攻击
			return false; 
		}

		$title= '编辑页面';
		$tpl = new Template();
		if(isset($_POST['id'])){
			$id=intval($_POST['id']);
			$tpl->updateMode($id);
			header('Location:?m=admin&c=tpl&a=dataList');
		}elseif(isset($_GET['id'])){
			$id=intval($_GET['id']);
			$data = $tpl->getOneData($id);
			include $this->display('tpl_content.tpl.php');
		}else{
			$id = $tpl->addModel();
			header('Location:?m=admin&c=tpl&a=dataList');
		}
	}

	public function updateTplSubmitAction(){
		$id = isset($_POST['id'])?$_POST['id']:(isset($_GET['id'])?$_GET['id']:0);
		$tpl = new Template();
		$tpl->updateTplModel($id);

		header('Location:?m=admin&c=tpl&a=dataList');
	}

	public function dataListAction(){
		$title= '页面列表';

		$tpl = new Template();
		$data = $tpl->lists();
		include $this->display('tpl_list.tpl.php');
	}

	public function delAction(){
		if(!isset($_GET['id'])){
			Core::showmessage('Invalid Operate');
		}
		
		$id = intval($_GET['id']);

		$tpl = new Template();
		$tpl->delData($id);

		header('Location:?m=admin&c=tpl&a=dataList');
	}

	public function previewAction(){
		if(!isset($_GET['id'])){
			Core::showmessage('Invalid Operate');
		}
		
		$id=intval($_GET['id']);
		$tpl = new Template();
		$data = $tpl->getOneData($id);
		if(file_exists(WEB_ROOT.$data['path'])){
			header('Location:'.$data['path']);
		}else
			echo Character::HTMLToDbDecode($data['html']);
	}
}
